// 这个文件就相当于子仓库
import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';
import request from 'umi-request';

const getData = () => {
  return request
    .get('/api/users')
    .then((response) => {
      return response;
    })
    .catch((error) => {
      console.log(error);
    });
};

export interface IndexModelState {
  name: string;
  count: number;
  list: any[];
}

export interface IndexModelType {
  // 如果一个变量是一个不会修改的字符串，那么可以直接将它的值作为类型
  namespace: 'index';
  state: IndexModelState;
  effects: {
    query: Effect;
    load: Effect;
  };
  reducers: {
    save: Reducer;
    increment: Reducer;
    decrement: Reducer;
    load2: Reducer;
    // 启用 immer 之后
    // save: ImmerReducer<IndexModelState>;
  };
  subscriptions: { setup: Subscription };
}

// IndexModel就是仓库的实例
const IndexModel: IndexModelType = {
  // 模块名称
  namespace: 'index',

  // 仓库状态
  state: {
    name: '',
    count: 7,
    list: [],
  },

  // 内置了saga中间件
  // 里面写异步函数
  effects: {
    *query({ payload }, { call, put }) {},
    *load({ payload }, { call, put }) {
      const res = yield call(getData);
      // console.log(res);
      yield put({ type: 'load2', payload: res.result });
    },
  },

  // reducers是同步函数，并且用来改变state
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    increment(state, action) {
      return {
        ...state,
        count: state.count + 1,
      };
    },
    decrement(state, action) {
      return {
        ...state,
        count: state.count - action.num,
      };
    },
    load2(state, action) {
      return {
        ...state,
        list: action.payload,
      };
    },
    // 启用 immer 之后
    // save(state, action) {
    //   state.name = action.payload;
    // },
  },
  // 监听url
  subscriptions: {
    setup({ dispatch, history }) {
      // console.log(history);
      return history.listen(({ pathname }) => {
        if (pathname === '/dva') {
          dispatch({
            type: 'load',
          });
        }
      });
    },
  },
};

export default IndexModel;
